<template>
  <div class="myTable">
    <el-table :data="tableData" border stripe style="width: 100%" :header-cell-style="mergeMehod"
      :row-class-name="rowClass" :span-method="mergeCloumn" @selection-change="SelectionChange"
      @cell-mouse-enter="cellMouseEnter" @cell-mouse-leave="cellMouseLeave">
      <el-table-column v-if="mutiSelect" type="selection" style="width: 55px;" />
      <MyColumn v-for="(item,i) in tableTitle" :key="i" :my-col="item" />
      <slot name="handleColumn" />
    </el-table>
    <el-pagination class="fy" background hide-on-single-page :page-size.sync="page.limit" :page-sizes="[2,5,10,20]"
      :current-page.sync="page.curPage" layout="total, sizes, prev, pager, next,jumper" :total="page.total"
      @size-change="getSize" @current-change="getCurChange" />
  </div>
</template>
   
<script>
import MyColumn from './MyColumn'
export default {
  name: 'MyTable',
  components: {
    MyColumn,
  },
  props: {
    tableData: {
      type: Array,
      default: () => {
        return []
      }
    },
    mutiSelect: {
      type: Boolean,
      default: () => {
        return false
      }
    },
    isMerge: {
      type: Boolean,
      default: () => {
        return false
      }
    },
    mergeName: {
      type: [String, Array],
      default: () => {
        return '' || []
      }
    },
    tableTitle: {
      type: Array,
      default: () => {
        return []
      }
    },
    page: {
      type: Object,
      default: function () {
        return {
          limit: 2,
        }
      }
    }
  },
  data() {
    return {
      total: 100,
      mergeData: null,
      sameRowArr: [],
      curRowArr: [],
    }
  },
  watch: {
    tableTitle: {
      deep: true,  // 深度监听
      immediate: true,
      handler(newVal) {
        return newVal
      }
    },
    tableData: {
      deep: true,  // 深度监听
      immediate: true,
      handler(newVal) {
        if (this.isMerge) {
          this.mergeData = this.dataMerge(newVal, Array.isArray(this.mergeName) ? [...this.mergeName] : this.mergeName )
          this.sameRowArr = this.getSameRow(newVal, this.mergeName)
          this.getStripe()
        }
      }
    },
    deep: true
  },
  created() {

  },
  methods: {
    SelectionChange(val) {//多行选中，暂时没用上
      console.log(val, 'ppo')
    },
    getSize(val) {
      this.$set(this.page, 'curPage', 1)
      this.$emit('getPageTable', this.page.curPage, val)
    },
    getCurChange(val) {
      this.$emit('getPageTable', val, this.page.limit)
    },
    mergeMehod({ row, column, rowIndex, columnIndex }) { //合并表头
      if (!this.isMerge) return
      for (let i = 0; i < row.length - 1; i++) {
        if (row[i].level === row[i + 1].level && row[i].labelClassName && row[i].labelClassName === row[i + 1].labelClassName && column.label === '') {
          return { display: 'none' }
        }
      }
      if (rowIndex === 0) {
        if (columnIndex === 0) {
          this.$nextTick(() => {
            if (document.getElementsByClassName(column.id).length !== 0) {
              document.getElementsByClassName(column.id)[0].setAttribute('rowSpan', 2);
              return false;
            }
          });
          return column;
        }
      }
    },
    mergeCloumn({ row, column, rowIndex, columnIndex }) {
      if (!this.isMerge) return
      if (this.mergeData) {
        //判断合并列
        let _row = column.property ? this.mergeData[column.property][rowIndex] : 1
        let _col = _row > 0 ? 1 : 0;
        return {
          rowspan: _row,
          colspan: _col
        }
      }
    },
    dataMerge: (tableData, mergeCol) => {
      // mergeData：最终输出合并的数据，
      // pos：记录每个列最终占了几行，可以理解成需要合并的每一列占据的行数，除第一列就是有几行合并就是几，其他列都是0
      let [mergeData, pos] = [{}, {}]
      //循环数据
      for (let i in tableData) {
        //循环数据内对象，查看有多少key
        for (let j in tableData[i]) {
          //如果只有一条数据时默认为1即可，无需合并
          if (i == 0) {
            mergeData[j] = [1];
            pos[j] = 0;
          } else {
            let [prev, next] = [tableData[i - 1], tableData[i]];
            //判断上一级别是否存在 ，如果存在判断两者key是否一致
            //判断是否有数组规定只允许那几列需要合并单元格的
            if (prev && prev[j] == next[j] && ((!mergeCol || mergeCol.length == 0) || mergeCol.includes(j))) {
              //如果当前与上一级数据相当，数组就加1 数组后面就添加一个0
              mergeData[j][pos[j]] += 1;
              mergeData[j].push(0)
            } else {
              mergeData[j].push(1);
              pos[j] = i;
            }
          }
        }
      }
      return mergeData;
    },
    // 合并行高亮------------------------------
    getSameRow(tableData, mergeCol) {
      let sameRowArr = [], sId = 0;
      //循环数据
      for (let i in tableData) {
        tableData[i].index = i;
        if (i == 0) {
          sameRowArr.push([i])
        } else {
          if (tableData[i][mergeCol] === tableData[i - 1][mergeCol]) {
            sameRowArr[sId].push(i)
          } else {
            sId = sId + 1;
            sameRowArr.push([i])
          }
        }
      }
      return sameRowArr
    },
    rowClass({ rowIndex }) {
      // 同一行
      let temArr = this.curRowArr
      for (let i = 0; i < temArr.length; i++) {
        if (rowIndex == temArr[i]) {
          return 'row_class'
        }
      }
    },
    cellMouseEnter(row) {
      if (!this.isMerge) return
      this.sameRowArr.forEach((arr) => {
        if (arr.indexOf(row.index) != -1) {
          this.curRowArr = arr
        }
      })
    },
    cellMouseLeave() {
      this.curRowArr = []
      this.getStripe()
    },
    // 斑马线
    getStripe() {
      if (!this.isMerge) return
      this.$nextTick(() => {
        let tr = document.getElementsByClassName("el-table__row");
        for (let i = 0; i < tr.length; i++) {
          if (tr[i].classList.contains('el-table__row--striped')) tr[i].classList.remove('el-table__row--striped')
        }
        for (let i = 0; i < this.sameRowArr.length; i++) {
          if (i % 2 != 0) {
            for (let j = 0; j < this.sameRowArr[i].length; j++) {
              tr[this.sameRowArr[i][j]].classList.add('el-table__row--striped')
            }
          }
        }
      })
    }
  }
}
</script>
<style lang="scss"  scoped>
::v-deep .el-table .row_class td {
  background: #f5f7fa !important;
}

.fy {
  margin: 10px auto 0;
  text-align: center;
}
</style>